<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .app{
            position: absolute;
            width: 100px;
            height: 100px;
            background-color: #000;
            cursor: pointer;
        }
    </style> 
</head>
<script>
    window.onload = function () {
        let drag = document.querySelector(".app")
        drag.onmousedown = function (e) {
            console.log(e);
            //鼠标与容器边界的距离
            let diffX = e.clientX - drag.offsetLeft //强制刷新，回流
            let diffY = e.clientY - drag.offsetTop
            drag.onmousemove = function (event) {
                console.log(event);
                let left = event.clientX - diffX
                let top = event.clientY - diffY
                if (left < 0) {
                    left = 0
                }else if (left > window.innerWidth - drag.offsetWidth) {
                    left = window.innerWidth - drag.offsetWidth
                }
                if (top < 0) {
                    top = 0
                }else if (top > window.innerHeight - drag.offsetHeight) {
                    top = window.innerHeight - drag.offsetHeight
                }
                drag.style.left = left + 'px';
                drag.style.top = top + 'px';
            }
            drag.onmouseup = function() {
                this.onmousemove = null
                this.onmouseup = null
            }
        } 
    }   
</script>   
<body>
    <div class="app"></div>
</body>
</html>